<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="合同标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入合同标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.bus_contract_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属场所" prop="placeId">
          <el-select v-model="queryParams.placeId" filterable placeholder="请选择场所" @change="handleQuery">
            <el-option
              v-for="item in placeList"
              :key="item.placeId"
              :label="item.placeName+'/ '+ item.status"
              :value="item.placeId">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="甲方联系人" prop="partyA">
        <el-input
          v-model="queryParams.partyA"
          placeholder="请输入甲方联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="乙方联系人" prop="partyB">
        <el-input
          v-model="queryParams.partyB"
          placeholder="请输入乙方联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经手人" prop="handler">
        <el-input
          v-model="queryParams.handler"
          placeholder="请输入经手人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:contract:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:contract:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:contract:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:contract:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="合同标题" align="center" prop="title" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_contract_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="合同时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }} </span><br>
          <span> 至 </span><br>
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span><br>
        </template>
      </el-table-column>
      <el-table-column label="签约场所" align="center" prop="placeId" />
      <el-table-column label="合同金额（元）" align="center" prop="contractAmount" >
        <template slot-scope="scope">
          <span>{{ scope.row.contractAmount }} </span>
        </template>
      </el-table-column>
      <el-table-column label="维护频率" align="center" prop="maintenanceFrequency" />
      <el-table-column label="甲方信息" align="center" prop="partyAContactPerson" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.partyA }} </span><br>
          <span>{{scope.row.partyAContactPhone}}</span><br>
          <span>{{scope.row.partyAContactEmail}} </span>
        </template>
      </el-table-column>
      <el-table-column label="乙方信息" align="center" prop="partyB" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.partyB }} </span><br>
          <span>{{scope.row.partyBContactPhone}} </span><br>
          <span>{{scope.row.partyBContactEmail}} </span>
        </template>
      </el-table-column>
      <el-table-column label="经手人" align="center" prop="handler" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.handler }} / {{scope.row.handlerPosition}} </span><br>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:contract:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:contract:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同信息，用于存储与场所相关的合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-divider content-position="center">合同基本信息</el-divider>
          <el-col :span="12">
            <el-form-item label="合同标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入合同标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number :min="0" v-model="form.sortOrder" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="合同状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.bus_contract_status" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约场所" prop="placeId">
              <el-select v-model="form.placeId" filterable placeholder="请选择场所" @change="handleSetContractAmount($event)" style="width: 280px">
                <el-option
                  v-for="(item, index) in placeList"
                  :key="item.placeId"
                  :label="item.placeName+'/台数: '+ item.elevatorNum +'/保养金额:'+ item.amount+'元(/年)'"
                  :value="item.placeId">
                </el-option>
              </el-select>
              <span style="color: #ef0c31">还没有签约场所，请先去场所信息中添加</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同时间" prop="dateRange">
              <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input-number v-model="form.contractAmount" :min="0" :step="10"  placeholder="请输入合同金额" />元
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经手人" prop="handler">
              <el-input v-model="form.handler" placeholder="请输入经手人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经手人电话" prop="handlerPhone">
              <el-input v-model="form.handlerPhone" placeholder="请输入经手人电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护频率" prop="maintenanceFrequency">
              <el-input v-model="form.maintenanceFrequency" placeholder="请输入维护频率" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-divider content-position="center">甲、乙方信息</el-divider>
          <el-col :span="12">
            <el-form-item label="甲方信息" prop="partyA">
              <el-input v-model="form.partyA" placeholder="请输入甲方信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方信息" prop="partyB">
              <el-input v-model="form.partyB" placeholder="请输入乙方信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方联系人" prop="partyAContactPerson">
              <el-input v-model="form.partyAContactPerson" placeholder="请输入甲方联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方联系人" prop="partyBContactPerson">
              <el-input v-model="form.partyBContactPerson" placeholder="请输入乙方联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方联系人职位" prop="partyAContactPosition">
              <el-input v-model="form.partyAContactPosition" placeholder="请输入甲方联系人职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方联系人职位" prop="partyBContactPosition">
              <el-input v-model="form.partyBContactPosition" placeholder="请输入乙方联系人职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方联系人电话" prop="partyAContactPhone">
              <el-input v-model="form.partyAContactPhone" placeholder="请输入甲方联系人电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方联系人电话" prop="partyBContactPhone">
              <el-input v-model="form.partyBContactPhone" placeholder="请输入乙方联系人电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方联系人邮箱" prop="partyAContactEmail">
              <el-input v-model="form.partyAContactEmail" placeholder="请输入甲方联系人邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方联系人邮箱" prop="partyBContactEmail">
              <el-input v-model="form.partyBContactEmail" placeholder="请输入乙方联系人邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-divider content-position="center">合同附件</el-divider>
          <el-col :span="24">
            <el-form-item label="合同图片" prop="images">
              <image-upload v-model="form.images"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="其他附件" prop="files">
              <file-upload v-model="form.files"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-divider content-position="center">合同内容</el-divider>
          <el-col :span="24">
          <el-form-item label="合同内容">
            <editor v-model="form.contractContent" :min-height="500"/>
          </el-form-item>
        </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/business/contract";
import { listPlace} from "@/api/business/place";

export default {
  name: "Contract",
  dicts: ['bus_contract_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 日期范围
      dateRange: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息，用于存储与场所相关的合同信息表格数据
      contractList: [],
      // 场所信息表格数据
      placeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        status: null,
        placeId: null,
        startDate: null,
        endDate: null,
        contractAmount: null,
        maintenanceFrequency: null,
        partyA: null,
        partyAContactPerson: null,
        partyAContactPosition: null,
        partyAContactPhone: null,
        partyAContactEmail: null,
        partyB: null,
        partyBContactPerson: null,
        partyBContactPosition: null,
        partyBContactPhone: null,
        partyBContactEmail: null,
        handler: null,
        handlerPhone: null,
        images: null,
        files: null,
        sortOrder: null,
        contractContent: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "合同标题不能为空", trigger: "blur" }
        ],
        placeId: [
          { required: true, message: "签约场所不能为空", trigger: "blur" }
        ],
        contractAmount: [
          { required: true, message: "合同金额不能为空", trigger: "blur" }
        ],
        maintenanceFrequency: [
          { required: true, message: "维护频率不能为空", trigger: "blur" }
        ],
        partyA: [
          { required: true, message: "甲方信息不能为空", trigger: "blur" }
        ],
        partyB: [
          { required: true, message: "乙方信息不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getPlaceList();
    this.getList();
  },
  methods: {
    /** 获取场所列表*/
    getPlaceList(){
      listPlace({pageSize: 10000}).then(response => {
        this.placeList = response.rows;
      });

    },
    /** 查询合同信息，用于存储与场所相关的合同信息列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        title: null,
        status: "草稿",
        contractId: null,
        placeId: null,
        startDate: null,
        endDate: null,
        dateRange: [],
        contractAmount: null,
        maintenanceFrequency: null,
        partyA: null,
        partyAContactPerson: null,
        partyAContactPosition: null,
        partyAContactPhone: null,
        partyAContactEmail: null,
        partyB: null,
        partyBContactPerson: null,
        partyBContactPosition: null,
        partyBContactPhone: null,
        partyBContactEmail: null,
        handler: null,
        handlerPhone: null,
        images: null,
        files: null,
        sortOrder: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        contractContent: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.dateRange = [];
      const contractId = row.contractId || this.ids
      getContract(contractId).then(response => {
        this.form = response.data;
        const { startDate, endDate } = response.data;
        // 将查询到的开始时间和结束时间赋值给 dateRange
        this.dateRange = [startDate, endDate ];
        this.open = true;
        this.title = "修改合同信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 把日期选择的值赋给开始时间和结束时间
          this.form.startDate = this.dateRange[0];
          this.form.endDate = this.dateRange[1];
          if (this.form.contractId != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 设置合同金额*/
    handleSetContractAmount(value){
      // 找到所选值的下标,获取该下标的合同金额
      this.selectedIndex = this.placeList.findIndex(option => option.placeId === value);
      this.form.contractAmount = this.placeList[this.selectedIndex].amount;

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$modal.confirm('是否确认删除合同信息，用于存储与场所相关的合同信息编号为"' + contractIds + '"的数据项？').then(function() {
        return delContract(contractIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
